﻿#ifndef HSV_CONVERTER
#define HSV_CONVERTER
	#define EPSILON         1.0e-4
	// linear space
	inline half3 RgbToHsv(half3 c)
	{
		float4 K = float4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
		float4 p = lerp(float4(c.bg, K.wz), float4(c.gb, K.xy), step(c.b, c.g));
		float4 q = lerp(float4(p.xyw, c.r), float4(c.r, p.yzx), step(p.x, c.r));
		float d = q.x - min(q.w, q.y);
		float e = EPSILON;
		return float3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
	}

		// linear space
	inline half3 HsvToRgb(half3 c)
	{
		half4 K = half4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
		half3 p = abs(frac(c.xxx + K.xyz) * 6.0 - K.www);
		return c.z * lerp(K.xxx, saturate(p - K.xxx), c.y);
			// return GammaToLinearSpace(p);
	}

	inline float3 offsetHsv(float3 color, float3 offset)
	{
		float3 hsv = RgbToHsv(color);
		hsv.x = frac(hsv.x + offset.x);
		hsv.yz *= offset.yz;
		return HsvToRgb(hsv);
	}

#endif